package de.dfki.asr.genesis2.sms.oauth;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

/**
 * Servlet implementation class FacebookOAuthService
 */
@WebServlet("/FacebookOAuthService")
public class FacebookOAuthService extends OAuthServlet {
	private static final long serialVersionUID = 1L;
    
    protected static final String FACEBOOK_ACCESS_TOKEN_SESSION = "FACEBOOK_ACCESS_TOKEN_SESSION";
    protected static final String redirect_uri = "http://localhost:8080/sms/FacebookOAuthService";
    protected static final String client_id = "400240100000830";
	protected static final String client_secret = "7c46a4fd701e7b0b122e3885c41f8373";
	protected static final String callback_url = "http://localhost:8080/Test/TestFacebookServlet";
	protected static final String accessToken_url = "https://graph.facebook.com/oauth/access_token?";
	protected static final String requestCode_url = "https://www.facebook.com/dialog/oauth/?";
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FacebookOAuthService() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String access_token = request.getParameter("access_token");
		String expires = request.getParameter("expires");
		String state = request.getParameter("state");
		String code = request.getParameter("code");
		
		System.out.println(state);
		System.out.println(code);
		
		String url = accessToken_url + 
					 "client_id=" + client_id +
					 "&client_secret=" + client_secret +
					 "&redirect_uri=" + redirect_uri + 
					 "&code=" + code;
		
		System.out.println(url);			 
		
		HttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(url);
		HttpResponse resp = client.execute(get);
		String body = EntityUtils.toString(resp.getEntity());
		String params[] = body.split("&");
		access_token = params[0].replace("access_token=", "");
		expires = params[1].replace("expires=", "");
		System.out.println(access_token);
		System.out.println(expires);
	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
